<style lang="less">
  .ue-module-wrap {

  }
</style>
<!--***-->
<template>
  <section class="ue-module-wrap">
    <!--工具条-->
    <el-col :span="24" style="margin-bottom: 10px">
      <el-button type="primary" @click="dialogInfo(null,'new')">新增</el-button>
    </el-col>
    <!--列表-->
    <el-table :data="tableData"
              highlight-current-row border
              @sort-change="sortChange"
              max-height="660"
              @selection-change="selsChange"
              v-loading="listLoading"
              style="width: 100%;">
      <el-table-column type="index" label="序号" width="60" >
      </el-table-column>
      <el-table-column prop="servicePromiseTypeName" label="服务分类" width="150" >
      </el-table-column>
      <el-table-column prop="serialNumber" label="服务排序" width="100" >
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="serviceAbstract" label="服务摘要" min-width="200" >
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button  type="primary" @click="dialogInfo(scope.row.id,'view')">查看 </el-button>
          <el-button  type="primary" @click="dialogInfo(scope.row.id,'edit')">编辑 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>
    <!--新增服务承诺 -->
    <el-dialog :title="dialogTitle" width="60%" :visible.sync="dialogVisible" :close-on-click-modal="false"  @close="resetInfoForm" class="ue-dialog-er-edit">
      <el-form :key="dialogKey" :model="objInfo" :rules="objInfoRules" label-width="120px" ref="objInfo">
        <el-row>
          <el-col :span="8">
            <el-form-item label="服务分类" prop="servicePromiseType">
              <el-select  v-model="objInfo.servicePromiseType" style="width: 100%" placeholder="请选择服务分类" :disabled="isDisabled">
                <el-option v-for="item in $store.getters.PROMISE_SERVICE_TYPE"
                           :key="item.dictVal"
                           :label="item.cnDictValname"
                           :value="item.dictVal"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="服务排序" prop="serialNumber">
              <el-input type="number" step="1" v-model="objInfo.serialNumber" placeholder="请设置服务排序" :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="f-mt10 f-mb10">
          <el-col :span="20">
            <el-form-item label="服务摘要" prop="serviceAbstract">
              <el-input type="textarea" v-model="objInfo.serviceAbstract" placeholder="请输入服务摘要" :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="服务详情" prop="introduction" >
              <quill-editor v-model="objInfo.introduction"
                            style="width: 100%;height: 150px"
                            ref="myQuillEditor"
                            class="editer"
                            :disabled="isDisabled">
              </quill-editor>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 70px">
          <el-col :span="20">
            <el-form-item label="服务图片">
              <el-upload
                :disabled="isDisabled"
                :on-success="handlePreviewImg"
                :on-remove="handleRemoveImg"
                :before-upload="beforeUploadImg"
                :on-preview="handlePictureCardPreview"
                class="upload-demo"
                action="/api/v2.0/admin/excellent_route/img"
                :limit="1"
                list-type="picture"
                :on-exceed="handleExceedImg"
                :file-list="fileListImg">
                <el-button size="small" type="primary">点击上传</el-button><label style="margin-left: 15px" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</label>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="服务图标">
              <el-upload
                :disabled="isDisabled"
                :on-success="handlePreviewIcon"
                :on-remove="handleRemoveIcon"
                :before-upload="beforeUploadIcon"
                :on-preview="handlePictureCardPreview"
                class="upload-demo"
                action="/api/v2.0/admin/excellent_route/img"
                :limit="1"
                list-type="picture"
                :on-exceed="handleExceedIcon"
                :file-list="fileListIcon">
                <el-button size="small" type="primary">点击上传</el-button><label style="margin-left: 15px" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</label>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button @click.native="resetInfoForm">关闭</el-button>
            <el-button type="primary" @click.native="handleSubmit" :loading="submitLoading"  :disabled="isDisabled">保存</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
    <!--图片预览-->
    <el-dialog :visible.sync="dialogVisiblePicture" size="tiny"  @close="closePictureCardPreview">
      <img width="100%" :src="dialogImageUrl" alt>
    </el-dialog>
  </section>
</template>
<script>
import {
  saveInfo,
  searchInfoList,
  getInfoById
} from '../../../api/stowage/ExcellentRouteServicePromise';
import {objToFilter, isEmpty, getSelectObect} from '../../../lib/util';
export default {
  data () {
    return {
      searchCondition: {
        'conditionName': null
      },
      sels: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: 'serialNumber',
      sortOrder: 'ascending',
      listLoading: false,
      tableData: [],
      // 弹窗1
      isDisabled: false,
      dialogVisible: false,
      submitLoading: false,
      dialogTitle: '新增服务承诺',
      dialogKey: 0,
      objInfo: {
        'id': null,
        'servicePromiseTypeName': null,
        'servicePromiseType': null,
        'serviceAbstract': null,
        'introduction': null,
        'image': null,
        'imageName': null,
        'icon': null,
        'iconName': null,
        'serialNumber': null
      },
      objInfoRules: {
        servicePromiseType: [
          {required: true, message: '请选择服务分类'}
        ],
        serviceAbstract: [
          {required: true, message: '请输入服务摘要'}
        ],
        introduction: [
          {required: true, message: '请输入服务详情'}
        ]
      },
      fileListImg: [],
      fileListIcon: [],
      imageUrl: [],
      iconUrl: [],
      // 图片预览
      dialogVisiblePicture: false,
      dialogImageUrl: null
    };
  },
  methods: {
    // 新增/修改/查看
    dialogInfo (id, type) {
      this.isDisabled = false;
      this.dialogVisible = true;
      if (isEmpty(id)) {
        this.dialogTitle = '新增服务';
        return null;
      } else if (type === 'edit') {
        this.dialogTitle = '编辑服务';
      } else {
        this.dialogTitle = '查看服务';
        this.isDisabled = true;
      }
      this.getDialogInfoById(id);
    },
    addressValue (value) {
      if (value) {
        return value;
      } else {
        return null;
      }
    },
    // 新增数据提交
    handleSubmit () {
      // 表单验证
      this.$refs['objInfo'].validate((valid) => {
        if (valid) {
          if (this.imageUrl[0]) {
            this.objInfo.image = this.imageUrl[0];
          } else {
            this.objInfo.image = null;
          };
          if (this.iconUrl[0]) {
            this.objInfo.icon = this.iconUrl[0];
          } else {
            this.objInfo.icon = null;
          };
          if (!this.objInfo.servicePromiseType) {
            this.$message.error('请选择服务分类');
            return;
          }
          this.submitLoading = true;
          this.isDisabled = true;
          this.objInfo.servicePromiseTypeName = getSelectObect(this.objInfo.servicePromiseType, 'dictVal', this.$store.getters.PROMISE_SERVICE_TYPE).cnDictValname;
          saveInfo(this.objInfo).then((res) => {
            this.isDisabled = false;
            this.submitLoading = false;
            if (res.data.successFlg === true) {
              this.dialogVisible = false;
              this.$message.success('保存/修改成功！');
              this.loadingLists('');
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            this.isDisabled = false;
            console.log(error);
          });
        } else {
          return false;
        }
      });
    },
    // 多选操作
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchTableList();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchTableList();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchTableList();
    },
    // 查询列表执行
    loadingLists (filter = '') {
      this.listLoading = true;
      searchInfoList({
        filters: filter,
        size: this.pageSize,
        page: this.currentPage,
        sorts: (this.sortProp === null ? '' : (this.sortOrder === 'ascending' ? '+' : '-') + this.sortProp)
      }).then(res => {
        if (res.data.successFlg) {
          this.tableData = res.data.detailModelList;
          this.currentPage = res.data.currPage;
          this.total = res.data.totalCount;
          this.pageSize = res.data.pageSize;
        };
        this.listLoading = false;
      });
    },
    // 查询调用
    searchTableList () {
      let filters = objToFilter(this.searchCondition);
      this.loadingLists(filters);
    },
    // 根据ID获取精品线路信息
    getDialogInfoById (id) {
      getInfoById(id).then(res => {
        if (res.data.successFlg) {
          let info = res.data.obj;
          this.objInfo = info;
          if (this.objInfo && this.objInfo.image) {
            this.fileListImg = [{name: '服务图片', url: this.objInfo.imgUrlHeader + this.objInfo.image}];
            this.imageUrl = [this.objInfo.image];
          } else {
            this.fileListImg = [];
            this.imageUrl = [];
          };
          if (this.objInfo && this.objInfo.icon) {
            this.fileListIcon = [{name: '服务图标', url: this.objInfo.imgUrlHeader + this.objInfo.icon}];
            this.iconUrl = [this.objInfo.icon];
          } else {
            this.fileListIcon = [];
            this.iconUrl = [];
          };
        };
      });
    },
    // 重置服务承诺表单
    resetInfoForm () {
      this.dialogVisible = false;
      this.dialogKey = Math.random() - 0.5;
      for (let p in this.objInfo) {
        if (this.objInfo[p] instanceof Array) {
          this.objInfo[p] = [];
        } else {
          this.objInfo[p] = null;
        }
      }
      this.fileListImg = [];
      this.fileListIcon = [];
      this.imageUrl = [];
      this.iconUrl = [];
    },
    // --------服务图片-图片上传
    //  图片预览
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisiblePicture = true;
    },
    //  图片预览清楚
    closePictureCardPreview () {
      this.dialogVisiblePicture = false;
      this.dialogImageUrl = null;
    },
    handleRemoveImg (file, fileList) {
      this.imageUrl = [];
    },
    handlePreviewImg (file) {
      this.imageUrl.push(file.obj);
    },
    beforeUploadImg (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 0.5;
      // const isLt2M = file.size / 1024 / 1024 <= 0.2;
      if (!isJPG) {
        this.$message.error('上传服务图片只能是 JPG 和 png格式!');
      }
      if (!isLt2M) {
        // this.$message.error('上传服务图片大小不能超过 500kb!');
        this.$message.error('上传线路图片大小不能超过 500kb!');
      }
      return isJPG && isLt2M;
    },
    handleExceedImg (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    // --------服务图标-图标图片上传
    handleRemoveIcon (file, fileList) {
      this.iconUrl = [];
    },
    handlePreviewIcon (file) {
      this.iconUrl.push(file.obj);
    },
    beforeUploadIcon (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      // const isLt2M = file.size / 1024 / 1024 < 2;
      const isLt2M = file.size / 1024 / 1024 <= 0.5;
      if (!isJPG) {
        this.$message.error('上传服务图标只能是 JPG 和 png格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传服务图标大小不能超过 500kb!');
        // this.$message.error('上传线路图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleExceedIcon (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill;
    }
  },
  mounted () {
    this.loadingLists('');
    this.$store.commit('initDict');
  }
};
</script>
